/**
 * @copyright SilverBiology, LLC
 * @author SilverBiology, LLC
 * @website http://www.silverbiology.com
*/

Ext.namespace('GBIF');
Ext.namespace('GBIF.GeoSpatial')



GBIF.GeoSpatial.CenterPanel = function(config){

	  OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";
	
	
	var layer1 = new OpenLayers.Layer.WMS(
			"Vectors"
		,	"http://labs.metacarta.com/wms/vmap0?"
		,	{
					layers: "basic"
				,	version: "1.0.0"
				, 	transparent: "true"
				, 	format: "image/png"
			}
		,	{
					allowOpacity: false
				,	allowDelete: false
				,	isBaseLayer:true
				,	checked:true
			}
	);
	var tabs = [];

	this.mapComponent = new GBIF.GeoSpatial.MapComponent({
						region: 'center'
					,	layers:[layer1]
				//	,	zoom: 10
			});
	
	this.mapComponent.map.setCenter(new OpenLayers.LonLat(-103 , 42), 7);	
	
	tabs.push(this.mapComponent);
	
	if (Config.GBIF.GeoSpatial.CenterPanel.showDataGridTabs) {
	
				this.tabmanager = new GBIF.GeoSpatial.TabManager({
								region: 'south'
							,	id: 'tabmanager'
							,	collapsible: true
							,	collapsedMode: 'mini'
							,	split: true
							,	tabConfig: {
										consoleShow: false  //Config.GBIF.GeoSpatial.TabManager.tabConfig.consoleShow
									,	georssShow:false  //Config.GBIF.GeoSpatial.TabManager.tabConfig.georssShow
									,	legendShow: false  //Config.GBIF.GeoSpatial.TabManager.tabConfig.legendShow
									,	featuredatagrid: true//Config.GBIF.GeoSpatial.TabManager.tabConfig.featuredatagrid
								}
				});
				
				 if (this.tabmanager.tabConfig.featuredatagrid) {
						 	
							this.featuredatagrid = this.tabmanager.featuredatagrid
						 	
						 	this.featuredatagrid.commit.on('click', this.senddata, this);
						 	
						 	this.featuredatagrid.on('rowClick', this.selectfeaturemap, this);
						 	
						 	this.featuredatagrid.on('deleteFeature', this.deletefeaturemap, this);
						 	
						 	this.featuredatagrid.on('centerToMap', this.moveMapToCenter, this);
						 	
						 	this.featuredatagrid.on('afterEdit', this.commitEditChanges, this);
				 }
				tabs.push(this.tabmanager);
	}
	
	
	Ext.apply(this, config, {
			border:false
		,	items:tabs	
		,	layout:'border'
		,	controlConfig:{
							clickControl: true  //Config.GBIF.GeoSpatial.CenterPanel.controlConfig.clickControl
						,	pointControl: true  //Config.GBIF.GeoSpatial.CenterPanel.controlConfig.pointControl
						,	lineControl: true  //Config.GBIF.GeoSpatial.CenterPanel.controlConfig.lineControl
						,	polygonControl: true  //Config.GBIF.GeoSpatial.CenterPanel.controlConfig.polygonControl
						,	selectControl: true  //Config.GBIF.GeoSpatial.CenterPanel.controlConfig.selectControl
						,	deleteControl: true  //Config.GBIF.GeoSpatial.CenterPanel.controlConfig.deleteControl
						,	modifyControl: true  //Config.GBIF.GeoSpatial.CenterPanel.controlConfig.modifyControl
					}
		,	listeners: {
				afterrender:function(){
						this.controlPanel();
					}
			}	
	});

	GBIF.GeoSpatial.CenterPanel.superclass.constructor.call(this,config);
}

Ext.extend(GBIF.GeoSpatial.CenterPanel, Ext.Panel, {
	
	callSaveFun:function(){
			this.scope.savetogrid();
		}

,	commitEditChanges:function(grid){
		var vectors=false;
		Ext.each(this.mapComponent.map.layers, function(maplayer){
					if( maplayer.name == "Feature Layer")
							vectors = maplayer;		
		},this);
		var feature = vectors.getFeatureById(grid.record.data.id);
		feature.properties = {
						name: grid.record.data.name
					,	attribute: grid.record.data.attribute
			}
	}

,	controlPanel:function(){
		    			
					/*
					 *	All function is depends on this grid 
					 */
					
					
					var controlArray = [];
					var remove = true;
					
					var vectors=false;
					Ext.each(this.mapComponent.map.layers, function(maplayer){
								if( maplayer.name == "Feature Layer")
										vectors = maplayer;		
					},this);
							
					if(!vectors){
						/* vectors =new OpenLayers.Layer.Vector(
								"Feature Layer"
							,	{
									allowOpacity: false
								,	allowDelete: false
								,	checked:true
								}
							);*/
							
		var saveStrategy = new OpenLayers.Strategy.Save();
/*							
		vectors = new OpenLayers.Layer.Vector("Feature Layer", {
				strategies: [new OpenLayers.Strategy.BBOX(), saveStrategy]
			,	projection: new OpenLayers.Projection("EPSG:4326")
			,	protocol: new OpenLayers.Protocol.WFS({
						version: "1.1.0"
					,	srsName: "EPSG:4326"
					,	url: "http://demo.opengeo.org/geoserver/wfs"
					,	featureNS :  "http://opengeo.org"
					,	featureType: "restricted"
					,	geometryName: "the_geom"
					,	schema: "http://demo.opengeo.org/geoserver/wfs/DescribeFeatureType?version=1.1.0&typename=og:restricted"
				})
		});
*/
		vectors = new OpenLayers.Layer.Vector("Feature Layer", {
				strategies: [new OpenLayers.Strategy.BBOX(), saveStrategy]
			,	projection: new OpenLayers.Projection("EPSG:4326")
			,	protocol: new OpenLayers.Protocol.WFS({
						version: "1.1.0"
					,	srsName: "EPSG:4326"
					,	url: "http://ogc.gbif.org/ows?service=WFS&typeName=geobon:scratchpad"					
					,	featureNS :  "http://gbif.org"
					,	featureType: "scratchpad"
					,	geometryName: "geom" //http://ogc.gbif.org/wfs/DescribeFeatureType?version=1.1.0&typename=geobon:scratchpad
					,	schema: "http://ogc.gbif.org/wfs/DescribeFeatureType?version=1.1.0&typename=geobon:scratchpad"
				})
		});
/*
    var attributeStore = new GeoExt.data.AttributeStore({
        url: "../../resources/api/getfeatureinfo-proxy.php?url=http://demo.opengeo.org/geoserver/wfs/DescribeFeatureType&version=1.1.0&typename=og:restricted"
			,	autoLoad: true
    });
*/
	}
					
					var mouseControl = new OpenLayers.Control.MouseDefaults({
								title: 'You can use the default mouse configuration'
							});
					controlArray.push(mouseControl);
					
					if (this.controlConfig.deleteControl) {
							remove = false;
							var remove = new GBIF.GeoSpatial.RemoveFeature(
										vectors
			 	                    ,	{	
											title: "Delete Feature"	
										,	onSelect: this.deleteFeature
										,	scope:this
										,	displayClass:'olControlRemoveFeature'
										}
								);
							controlArray.push(remove);	
					}
					
					
					if (this.controlConfig.modifyControl) {
							remove = false;
							var modify= new OpenLayers.Control.ModifyFeature(
										vectors
									,	{
											title: "Modify Feature"
										,	onModificationEnd:this.callSaveFun
										,	scope:this
										}
									);
							controlArray.push(modify);			
					}
					
					var save = new OpenLayers.Control.Button({
						        title: "Save Changes",
						        trigger: function() {
						            if(modify.feature) {
						                modify.selectControl.unselectAll();
						            }
						            saveStrategy.save();
						        },
						        displayClass: "olControlSaveFeatures"
						    });
	
					controlArray.push(save);
					
					if (this.controlConfig.selectControl) {
							remove = false;
							var SelectFeature= new OpenLayers.Control.SelectFeature(
												vectors
						                    ,	{	title: "Select Feature"	
												,	onSelect:this.onselectfeature	
												,	deactivate:this.unselectFeature 
												,	scope:this
												,	displayClass:"olControlSelectFeature"
												}
											);
							controlArray.push(SelectFeature);				
					}
					
					if (this.controlConfig.polygonControl) {
							remove = false;
							var drawpolygon = new OpenLayers.Control.DrawFeature(
				                    		vectors
										, 	OpenLayers.Handler.Polygon
										,	{
												title: "Polygon Feature"
											//,	clickout:true
											,	displayClass:'olControldrawpolygon'
											,	scope:this
											,	multi:true
											,	featureAdded:this.callSaveFun
											}
								);
							controlArray.push(drawpolygon);	
					}
					
					if (this.controlConfig.lineControl) {
							remove = false;
							var drawline = new OpenLayers.Control.DrawFeature(
					                    		vectors
											, 	OpenLayers.Handler.Path
											,	{
													title: "Line Feature"
												,	clickout:true
												,	displayClass:'olControldrawline'
												,	featureAdded:this.callSaveFun
												,	scope:this
												}
								);
							controlArray.push(drawline);	
					}
					
					if (this.controlConfig.pointControl) {
								remove = false;
								var drawpoint= new OpenLayers.Control.DrawFeature(
						                    	vectors
											, 	OpenLayers.Handler.Point
											,	{
													title: "Point Feature"
												,	clickout:true	
												,	displayClass:'olControldrawpoint'
												,	featureAdded:this.callSaveFun
												,	scope:this
												}
					    	     );
							controlArray.push(drawpoint);	 
					}
					
					if (this.controlConfig.clickControl) {
							OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
					                defaultHandlerOptions: {
					                    'single': true,
					                },
					                initialize: function(options) {
					                    this.handlerOptions = OpenLayers.Util.extend(
					                        {}, this.defaultHandlerOptions
					                    );
					                    OpenLayers.Control.prototype.initialize.apply(
					                        this, arguments
					                    ); 
					                    this.handler = new OpenLayers.Handler.Click(
					                        this, {
					                            'click': this.onClick
					                        }, this.handlerOptions
					                    );
					                }, 
					
					                onClick: function(evt) {
										var xy = evt.xy;
					                	Ext.each(this.map.layers,function(maplayer){
												if (maplayer.querable) {
														GBIF.GeoSpatial.BUS.fireEvent('sendRequest', maplayer,xy, this);
												}
										},this)
									}
							 });
								
								var activeclick = new OpenLayers.Control.Click({
								    	    title: "Inspect Layers"
										,	allowSelection:true
										,	displayClass: "olControlClickFeature"
					        			,	handlerOptions: {
					                            "single": true
					                        }
										,	trigger: function() {
												Ext.each(panel.controls,function(control){
														if(control.title != 'Single Click'|| control.title != 'Inspect Layers' )
																control.deactivate();
												});
												if(singleclick.active){
													activeclick.deactivate();
												}else{
													activeclick.activate();
												}
											}
					    			});
							controlArray.push(activeclick);		
						}
					if(!remove){
						this.mapComponent.map.addLayer(vectors);	
					}else{
						this.tabmanager.remove(this.featuredatagrid);
					}
					var panel = new OpenLayers.Control.Panel();
					
					panel.addControls(controlArray);
					panel.defaultControl=mouseControl;
					
					this.mapComponent.map.addControl(panel);		
					panel.activate();
		}
		
	,	moveMapToCenter:function(lon,lat){
				this.mapComponent.map.setCenter(new OpenLayers.LonLat(lon || 0 , lat || 0));
			}
	
	,	unselectFeature: function(){
				this.unselectAll();
				if (this.active) {
			            this.handlers.feature.deactivate();
			            if(this.handlers.box) {
			                this.handlers.box.deactivate();
			            }
			            if(this.layers) {
			                this.map.removeLayer(this.layer);
			            }
			        }
				return OpenLayers.Control.prototype.deactivate.apply(
            			this, arguments
        		)
			}	
	
	,	selectfeaturemap:function(grid,index){
			var rec = grid.store.getAt(index);
			var veclayer;
				Ext.each(this.mapComponent.map.layers, function(maplayer){
						if( maplayer.name == "Feature Layer")
							veclayer = maplayer;		
				},this);
			var feature = veclayer.getFeatureById(rec.data.id);
			var selfeature = this.mapComponent.map.getControlsByClass('OpenLayers.Control.SelectFeature');
			selfeature[0].unselectAll();
			selfeature[0].select(feature);
		}
	
	,	onselectfeature:function(layer){
			this.tabmanager.setActiveTab(this.featuredatagrid);
			var index = this.featuredatagrid.store.findExact("id",layer.fid);
			this.featuredatagrid.getSelectionModel().selectRow(index);
		}
		
	,	savetogrid: function(){
			this.tabmanager.setActiveTab(this.featuredatagrid);
			var point=[];
			Ext.each(this.mapComponent.map.layers, function(maplayer){
				if( maplayer.name == "Feature Layer"){
					maplayer.setZIndex(10000);
					Ext.each(maplayer.features,function(feature){
							feature.fid = feature.id;	
							switch(feature.geometry.CLASS_NAME) {
								case "OpenLayers.Geometry.Point":
									var type = "Point"
									break;
								case "OpenLayers.Geometry.LineString":
									var type = "Line"
									break;
								case "OpenLayers.Geometry.Polygon":
									var type = "Polygon"
									break;
								}
								var data = {
											"geometry": {
													"type": "og:restricted"//type
												, 	"coordinates": [feature.geometry.bounds.getCenterLonLat()]
												}
										,	state:feature.state
										, 	"type": "Feature"
										, 	"properties": {
														"name": "the_geom"//(typeof feature.properties == 'undefined')? "" : feature.properties.name
													,	"attribute": (typeof feature.properties == 'undefined')? "" : feature.properties.attribute                   
												} 
										, "id": feature.id
										}
								point.push(data);
						},this);
					}
				},this);
			this.featuredatagrid.store.loadData(point);	
		}	
	
	,	senddata: function(){
			var params=[];
			Ext.each(this.featuredatagrid.store.data.items,function(items){
						params.push(items.json);
				},this);
			Ext.Ajax.request({
				url: "../../resources/api/proxy.php"
			,	method: 'POST'
			,	scope:this
			,	params:Ext.encode(params)
			,	success: function(responseObject){
						GBIF.GeoSpatial.Notice.msg('Status', 'Saved Sucessfully.');
 				}
			,	failure: function(responseObject){
						GBIF.GeoSpatial.Notice.msg('Status', 'Saved Sucessfully.');
 					}	
			}, this);
			
		}
	
	,	deletefeaturemap:function(){
				Ext.each(this.mapComponent.map.layers, function(maplayer){
						if( maplayer.name == "Feature Layer")
								veclayer = maplayer;		
					},this);
				this.deleteFeature(veclayer.selectedFeatures);	
		}	
	
	,	deleteFeature:function(geometry){
				var veclayer;
				Ext.each(this.mapComponent.map.layers, function(maplayer){
						if( maplayer.name == "Feature Layer")
							veclayer = maplayer;		
				},this);
				veclayer.removeFeatures(geometry);
				this.savetogrid(veclayer);
		}	
});